(function() {
    'use strict';

    angular
        .module('byibserverApp')
        .controller('CrowdDialogController', CrowdDialogController);

    CrowdDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', '$q', 'DataUtils', 'entity', 'Crowd', 'Product'];

    function CrowdDialogController ($timeout, $scope, $stateParams, $uibModalInstance, $q, DataUtils, entity, Crowd, Product) {
        var vm = this;

        vm.crowd = entity;
        vm.clear = clear;
        vm.byteSize = DataUtils.byteSize;
        vm.openFile = DataUtils.openFile;
        vm.save = save;
        getProduct();

        function getProduct() {
            Product.query({
                page: 0,
                size: 1000,
            }, function (data,headers) {
                vm.products = data;
            }, function (error) {

            });
        }
        $q.all([vm.crowd.$promise, vm.products.$promise]).then(function() {
            if (!vm.crowd.productId) {
                return $q.reject();
            }
            return Product.get({id : vm.crowd.productId}).$promise;
        }).then(function(product) {
            vm.products.push(product);
        });

        $timeout(function (){
            angular.element('.form-group:eq(1)>input').focus();
        });

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }

        function save () {
            vm.isSaving = true;
            if (vm.crowd.id !== null) {
                Crowd.update(vm.crowd, onSaveSuccess, onSaveError);
            } else {
                Crowd.save(vm.crowd, onSaveSuccess, onSaveError);
            }
        }

        function onSaveSuccess (result) {
            $scope.$emit('byibserverApp:crowdUpdate', result);
            $uibModalInstance.close(result);
            vm.isSaving = false;
        }

        function onSaveError () {
            vm.isSaving = false;
        }


    }
})();
